/*
 * CacheController.cpp
 *
 *  Created on: 03.12.2012
 *      Author: zheka
 */

#include "CacheController.hpp"
#include "CacheTask.hpp"
#include "pthread/ScopedLock.hpp"

CacheEntry * CacheController::get(Context & context, HttpRequest request) {
	ScopedLock lock(mutex);
	std::string url = request.getHttpQuery();
	std::map<std::string, CacheEntry*>::iterator it = cacheEntries.find(url);
	if (it != cacheEntries.end()) {
		CacheEntry * cacheEntry = it->second;
		if (cacheEntry->getClientCount() == 0 && cacheEntry->isDisposable()) {
			remove(cacheEntry);
			delete cacheEntry;

		} else {

			return it->second;
		}
	}

	{
		CacheEntry * cacheEntry = new CacheEntry();
		cacheEntries.insert(
				std::pair<std::string, CacheEntry*>(url, cacheEntry));
		cacheEntriesMap.insert(
				std::pair<CacheEntry*, std::string>(cacheEntry, url));

		context.registerNewTask(new CacheTask(cacheEntry, request));

		return cacheEntry;
	}
}

void CacheController::remove(CacheEntry * entry) {
	ScopedLock lock(mutex);
	std::map<CacheEntry*, std::string>::iterator it = cacheEntriesMap.find(
			entry);
	cacheEntries.erase(cacheEntries.find(it->second));
	cacheEntriesMap.erase(it);
}
